<?php

namespace Iwesen\Sem\Track\Advertisers;

use Illuminate\Support\Facades\Log;

class Gdt
{

    /**
     * @param array  $param 
     */
    public function callback($param)
    {
        if(!isset($param['access_token']) || !$param['access_token']){
            throw new \Exception( 'access_token is not a exist !');
        }
        if(!isset($param['account_id']) || !$param['account_id']){
            throw new \Exception( 'account_id is not a exist !');
        }
        if(!isset($param['actions']) || !is_array($param['actions'])){
            throw new \Exception( 'actions is not a exist !');
        }

        $data = [
            'account_id'=>$param['account_id'],
            'actions'=>$param['actions']
        ];
        $urlObj = [
            'access_token'=>$param['access_token'],
            'timestamp'=>time(),
            'nonce'=>'sem-track-'.time()
        ];
        $url = "https://api.e.qq.com/v1.1/user_actions/add?".$this->ToUrlParams($urlObj);
        try {
            $result = (new Request())->_request($url,'',$data);
            $data = json_decode($result,true);
            if ($data['code'] === 0) {
                return 'success';
            }
            return $data['message'];
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), $e->getCode(), $e);
        } 
    }

    /**
     * 拼接签名字符串
     * @param array $urlObj
     * @return 返回已经拼接好的字符串
     */
    private function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v) {
            if ($k != "sign") {
                $buff .= $k . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        return $buff;
    }
}